<?php

namespace App\Http\Controllers\DataV;

use App\Http\Controllers\Controller;
use App\Models\OrderModel;
use App\Utils\ApiResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class OrderWeightDataVController extends Controller
{
    use ApiResponse;

    /**
     * 各省下单量(重量)占比
     * @param Request $request
     * @return JsonResponse
     */
    public function getProvinceOrderWeightSumList(Request $request): JsonResponse
    {
        $date = $request->input('date') ? $request->input('date') : ['2024-07-01', '2024-09-30'];
        if (!is_array($date) || count($date) < 2)
            return $this->fail([210001, '日期格式错误']);
        $collection = OrderModel::where('pay_status', 1)->where('goods_total', '>', 0)->whereNotNull('province')
            ->whereBetween('order_date', $date)
            ->selectRaw('province, SUM(total_weight) AS total_weight')->groupBy('province')->get();
        $totalWeight = array_sum($collection->pluck('total_weight')->toArray());
        $collection->each(function ($item) use ($totalWeight) {
            $item['percent'] = round($item->total_weight / $totalWeight * 100, 2);
            $item['province_text'] = $this->getProvinceText($item->province);
            return $item;
        });
        return $this->success($collection);
    }

    /**
     * 获取省名称
     * @param $province
     * @return string
     */
    private function getProvinceText($province): string
    {
        $provinceMap = [
            '110000' => '北京',
            '120000' => '天津',
            '130000' => '河北',
            '140000' => '山西',
            '150000' => '内蒙古',
            '210000' => '辽宁',
            '220000' => '吉林',
            '230000' => '黑龙江',
            '310000' => '上海',
            '320000' => '江苏',
            '330000' => '浙江',
            '340000' => '安徽',
            '350000' => '福建',
            '360000' => '江西',
            '370000' => '山东',
            '410000' => '河南',
            '420000' => '湖北',
            '430000' => '湖南',
            '440000' => '广东',
            '450000' => '广西',
            '460000' => '海南',
            '500000' => '重庆',
            '510000' => '四川',
            '520000' => '贵州',
            '530000' => '云南',
            '540000' => '西藏',
            '610000' => '陕西',
            '620000' => '甘肃',
            '630000' => '青海',
            '640000' => '宁夏',
            '650000' => '新疆',
            '710000' => '台湾',
            '810000' => '香港',
            '820000' => '澳门',
        ];
        return $provinceMap[$province] ?? '其他';
    }
}
